<template>
  <div class="user-analytics-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户数据分析</span>
          <div class="date-range-picker">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="handleDateRangeChange"
            ></el-date-picker>
          </div>
        </div>
      </template>
      
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ totalUsers }}</div>
            <div class="stat-label">总用户数</div>
            <div class="stat-change" :class="{ positive: newUsersChange > 0 }">
              <span>{{ newUsersChange > 0 ? '+' : '' }}{{ newUsersChange }}%</span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ activeUsers }}</div>
            <div class="stat-label">活跃用户数</div>
            <div class="stat-change" :class="{ positive: activeUsersChange > 0 }">
              <span>{{ activeUsersChange > 0 ? '+' : '' }}{{ activeUsersChange }}%</span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ retentionRate }}%</div>
            <div class="stat-label">用户留存率</div>
            <div class="stat-change" :class="{ positive: retentionRateChange > 0 }">
              <span>{{ retentionRateChange > 0 ? '+' : '' }}{{ retentionRateChange }}%</span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-card>
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-number">{{ avgSessionDuration }}分钟</div>
            <div class="stat-label">平均会话时长</div>
            <div class="stat-change" :class="{ positive: avgSessionDurationChange > 0 }">
              <span>{{ avgSessionDurationChange > 0 ? '+' : '' }}{{ avgSessionDurationChange }}%</span>
              <span class="change-label">较上期</span>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 图表区域 -->
      <div class="charts-container">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户增长趋势</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <canvas ref="growthChart"></canvas>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户活跃度分布</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <canvas ref="activityChart"></canvas>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户地域分布</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <canvas ref="regionChart"></canvas>
          </div>
        </el-card>
        
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>用户设备分布</span>
            </div>
          </template>
          <div class="chart-wrapper">
            <canvas ref="deviceChart"></canvas>
          </div>
        </el-card>
      </div>
      
      <!-- 活跃用户列表 -->
      <el-card class="active-users-card">
        <template #header>
          <div class="chart-header">
            <span>最近活跃用户</span>
          </div>
        </template>
        <el-table :data="activeUsersList" style="width: 100%">
          <el-table-column prop="userId" label="用户ID" width="80"></el-table-column>
          <el-table-column label="用户信息" min-width="200">
            <template #default="scope">
              <div class="user-info">
                <el-avatar :size="40" :src="scope.row.avatar"></el-avatar>
                <div class="user-details">
                  <div class="username">{{ scope.row.username }}</div>
                  <div class="user-email">{{ scope.row.email }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="lastLogin" label="最近登录时间" width="180"></el-table-column>
          <el-table-column prop="loginCount" label="登录次数" width="100"></el-table-column>
          <el-table-column prop="level" label="用户等级" width="100">
            <template #default="scope">
              <el-tag :type="getLevelType(scope.row.level)">{{ scope.row.level }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import * as echarts from 'echarts'

// 日期范围选择
const dateRange = ref([])

// 统计数据
const totalUsers = ref(0)
const activeUsers = ref(0)
const retentionRate = ref(0)
const avgSessionDuration = ref(0)
const newUsersChange = ref(0)
const activeUsersChange = ref(0)
const retentionRateChange = ref(0)
const avgSessionDurationChange = ref(0)

// 活跃用户列表
const activeUsersList = ref([])

// 图表实例引用
  const growthChart = ref(null)
  const activityChart = ref(null)
  const regionChart = ref(null)
  const deviceChart = ref(null)
  let growthChartInstance = null
  let activityChartInstance = null
  let regionChartInstance = null
  let deviceChartInstance = null

// 获取用户等级标签样式
const getLevelType = (level) => {
  if (level >= 5) return 'primary'
  if (level >= 3) return 'success'
  return 'info'
}

// 获取统计数据
const fetchAnalyticsData = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  
  // 统计数据
  totalUsers.value = 1258
  activeUsers.value = 832
  retentionRate.value = 76.5
  avgSessionDuration.value = 18.5
  
  // 变化率
  newUsersChange.value = 5.2
  activeUsersChange.value = 3.8
  retentionRateChange.value = -1.2
  avgSessionDurationChange.value = 2.5
  
  // 活跃用户列表
  activeUsersList.value = [
    {
      userId: 1,
      username: '张三',
      email: 'zhangsan@example.com',
      avatar: 'https://picsum.photos/100/100?random=1',
      lastLogin: '2023-07-05 15:30:00',
      loginCount: 45,
      level: 5
    },
    {
      userId: 2,
      username: '李四',
      email: 'lisi@example.com',
      avatar: 'https://picsum.photos/100/100?random=2',
      lastLogin: '2023-07-05 14:20:00',
      loginCount: 38,
      level: 4
    },
    {
      userId: 3,
      username: '王五',
      email: 'wangwu@example.com',
      avatar: 'https://picsum.photos/100/100?random=3',
      lastLogin: '2023-07-05 13:45:00',
      loginCount: 62,
      level: 5
    }
  ]
  
  // 更新图表
  updateGrowthChart()
  updateActivityChart()
  updateRegionChart()
  updateDeviceChart()
}

// 更新用户增长趋势图表
const updateGrowthChart = () => {
  if (!growthChart.value) return
  
  // 销毁旧图表
  if (growthChartInstance) {
    growthChartInstance.dispose()
  }
  
  growthChartInstance = echarts.init(growthChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['新增用户', '活跃用户'],
      top: 0
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月'],
      axisPointer: {
        type: 'shadow'
      }
    },
    yAxis: {
      type: 'value',
      min: 0
    },
    series: [
      {
        name: '新增用户',
        type: 'line',
        data: [120, 190, 300, 220, 280, 350],
        lineStyle: {
          color: '#409EFF',
          width: 3
        },
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.1)'
        },
        smooth: true
      },
      {
        name: '活跃用户',
        type: 'line',
        data: [180, 240, 320, 360, 420, 480],
        lineStyle: {
          color: '#67C23A',
          width: 3
        },
        areaStyle: {
          color: 'rgba(103, 194, 58, 0.1)'
        },
        smooth: true
      }
    ]
  }
  
  growthChartInstance.setOption(option)
}

// 更新用户活跃度分布图表
const updateActivityChart = () => {
  if (!activityChart.value) return
  
  // 销毁旧图表
  if (activityChartInstance) {
    activityChartInstance.dispose()
  }
  
  activityChartInstance = echarts.init(activityChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: ['每日活跃', '每周活跃', '每月活跃', '偶尔活跃', '不活跃']
    },
    yAxis: {
      type: 'value',
      min: 0
    },
    series: [
      {
        name: '用户数量',
        type: 'bar',
        data: [320, 280, 150, 180, 128],
        itemStyle: {
          color: function(params) {
            const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
            return colors[params.dataIndex]
          }
        }
      }
    ]
  }
  
  activityChartInstance.setOption(option)
}

// 更新用户地域分布图表
const updateRegionChart = () => {
  if (!regionChart.value) return
  
  // 销毁旧图表
  if (regionChartInstance) {
    regionChartInstance.dispose()
  }
  
  regionChartInstance = echarts.init(regionChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'center'
    },
    series: [
      {
        name: '用户数量',
        type: 'pie',
        radius: '60%',
        center: ['40%', '50%'],
        data: [
          {value: 280, name: '北京', itemStyle: {color: '#409EFF'}},
          {value: 240, name: '上海', itemStyle: {color: '#67C23A'}},
          {value: 180, name: '广州', itemStyle: {color: '#E6A23C'}},
          {value: 150, name: '深圳', itemStyle: {color: '#F56C6C'}},
          {value: 408, name: '其他', itemStyle: {color: '#909399'}}
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  regionChartInstance.setOption(option)
}

// 更新用户设备分布图表
const updateDeviceChart = () => {
  if (!deviceChart.value) return
  
  // 销毁旧图表
  if (deviceChartInstance) {
    deviceChartInstance.dispose()
  }
  
  deviceChartInstance = echarts.init(deviceChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'right',
      top: 'center'
    },
    series: [
      {
        name: '用户数量',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        data: [
          {value: 480, name: 'iOS', itemStyle: {color: '#409EFF'}},
          {value: 520, name: 'Android', itemStyle: {color: '#67C23A'}},
          {value: 180, name: 'Web', itemStyle: {color: '#E6A23C'}},
          {value: 78, name: '其他', itemStyle: {color: '#909399'}}
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  deviceChartInstance.setOption(option)
}

// 日期范围变化处理
const handleDateRangeChange = () => {
  fetchAnalyticsData()
}

// 页面挂载时获取数据
onMounted(() => {
  // 设置默认日期范围为最近30天
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(startDate.getDate() - 30)
  dateRange.value = [startDate, endDate]
  
  fetchAnalyticsData()
})

// 监听窗口大小变化，重绘图表
const handleResize = () => {
  updateGrowthChart()
  updateActivityChart()
  updateRegionChart()
  updateDeviceChart()
}

window.addEventListener('resize', handleResize)

// 组件卸载时清理
const cleanup = () => {
  window.removeEventListener('resize', handleResize)
  if (growthChartInstance) growthChartInstance.dispose()
  if (activityChartInstance) activityChartInstance.dispose()
  if (regionChartInstance) regionChartInstance.dispose()
  if (deviceChartInstance) deviceChartInstance.dispose()
}

// 生命周期清理
import { onUnmounted } from 'vue'
onUnmounted(() => {
  cleanup()
})
</script>

<style scoped>
.user-analytics-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-range-picker {
  display: flex;
  align-items: center;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.stat-change {
  font-size: 12px;
  color: #F56C6C;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-change.positive {
  color: #67C23A;
}

.change-label {
  color: #909399;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.chart-card {
  height: 350px;
}

.chart-header {
  font-weight: bold;
  color: #303133;
}

.chart-wrapper {
  height: calc(100% - 50px);
  position: relative;
}

.active-users-card {
  margin-top: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.user-email {
  font-size: 12px;
  color: #909399;
}

@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }
}

@media (max-width: 576px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>